/*
 * thread.h
 *
 *  Created on: 2008-8-13
 *      Author: fanliangliang
 */

#ifndef THREAD_H_
#define THREAD_H_

#include "bits/runnable.h"
#include <cstdlib>
#include <exception>
#include <string>

BEGIN_NAMESPACE_TOXIC

class Thread : public Runnable {
	CLASS_UNCOPYABLE(Thread)
public:
	template <class T>
	explicit Thread(const T& op)
	:_target(detail::transform(op))
	,_tid(0)
	,_handle(0) {
	}

	Thread();
	virtual ~Thread();
	virtual void run();

	void start();
	void join();
	size_t id() const;

	static void yield();
	static void sleep(unsigned long ms);
	static size_t self();

private:
#if defined(PLATFORM_WIN32)
	static __stdcall unsigned start_routine(void* arg);
#else
	static void* start_routine(void* arg);
#endif

private:
	Runnable* _target;
	size_t _tid;
	void* _handle;
};

bool operator==(const Thread& lhs, const Thread& rhs);
bool operator!=(const Thread& lhs, const Thread& rhs);

class ThreadException : public std::exception {
public:
	explicit ThreadException(const std::string& what = "") throw()
	:_what(what) {
	}

	virtual ~ThreadException() throw() {
	}

	virtual const char* what() const throw() {
		return _what.c_str();
	}

private:
	std::string _what;
};

END_NAMESPACE_TOXIC

#endif /* THREAD_H_ */
